# coding=utf-8
import threading
import time

import requests
from catch_logging import CatchLogging
from data_analysis import data_analysis
from json_db import JsonDB


# 提交数据的线程
class PostDataThread(threading.Thread):

    __url = ''
    __data = None

    def __init__(self, url, data):
        threading.Thread.__init__(self)
        self.__url = url
        self.__data = data

    def start(self):
        if self.__data is not None:
            try:
                self.__data['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                self.__data['tarData'] = data_analysis(self.__data['msgStr'], self.__data['dataType'])
                JsonDB.insert(self.__data)
                if len(self.__url) > 0:
                    response = requests.post(url=self.__url, json=self.__data, headers={'Content-Type': 'application/json;charset=UTF-8'})
                    CatchLogging.info('请求返回{}'.format(response))
            except Exception as e:
                CatchLogging.error(e.message)

    @classmethod
    def post_data(cls, post_url, data):
        # 创建一个线程并发送数据
        PostDataThread(post_url, data).start()



